package com.kui.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kui.enums.UserEnums;
import com.kui.constant.UserConstant;
import com.kui.exception.BusinessException;
import com.kui.exception.ErrorCode;
import com.kui.exception.ThrowUtils;
import com.kui.mapper.UserMapper;
import com.kui.model.dto.user.LoginRequest;
import com.kui.model.dto.user.RegisterRequest;
import com.kui.model.dto.user.UserQueryRequest;
import com.kui.model.entity.User;
import com.kui.model.vo.LoginUserVO;
import com.kui.model.vo.UserVO;
import com.kui.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lack
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-01-19 14:43:09
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;

    /**
     * 用户注册
     *
     * @param registerRequest
     * @return
     */
    @Override
    public Long userRegister(RegisterRequest registerRequest) {
        User user = new User();
        String userPassword = registerRequest.getUserPassword();
        String checkPassword = registerRequest.getCheckPassword();
        String userAccount = registerRequest.getUserAccount();
        //进行参数校验
        if (StrUtil.hasBlank(userAccount, userPassword, checkPassword)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        if (userPassword.length() < 6) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "密码长度不能小于6");
        }
        if (!userPassword.equals(checkPassword)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "两次密码不一致");
        }
        // 查询账户是否重复
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("userAccount", userAccount);
        Long hasUser = userMapper.selectCount(query);
        if (hasUser > 0) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "账户重复");
        }
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword(userPassword));
        //默认角色为普通用户
        user.setUserRole(UserEnums.USER.getValue());
        user.setUserName("游客");
        boolean save = this.save(user);
        if (!save) {
            ThrowUtils.throwIf(true, ErrorCode.SYSTEM_ERROR, "注册失败,数据库异常");
        }
        Long resultId = user.getId();
        return resultId;
    }

    @Override
    public LoginUserVO userLogin(LoginRequest loginRequest, HttpServletRequest request) {
        String userAccount = loginRequest.getUserAccount();
        String userPassword = loginRequest.getUserPassword();
        if (StrUtil.hasBlank(userAccount, userPassword)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        if (userPassword.length() < 6) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "密码长度不能小于6");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserAccount, userAccount);
        wrapper.eq(User::getUserPassword, encryptPassword(userPassword));
        User user = userMapper.selectOne(wrapper);
        if (ObjectUtils.isEmpty(user)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, "用户名或密码错误");
        }
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        LoginUserVO loginUserVO = loginUser(user);
        return loginUserVO;
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        //判断是否登录
        Object object = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) object;
        if (ObjectUtil.isNotEmpty(currentUser)) {
            Long currentUserId = currentUser.getId();
            if (currentUser == null || currentUserId == null) {
                ThrowUtils.throwIf(true, ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
            }
            //可以直接返回上面拿到的数据，但是因为是缓存的原因可能会出现数据没更新的情况，查询数据库
            currentUser = this.getById(currentUserId);
            if (currentUser == null) {
                ThrowUtils.throwIf(true, ErrorCode.NOT_LOGIN_ERROR);
            }
        } else {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //将数据库中拿到的数据返回出去
        return currentUser;
    }

    /**
     * 注销（退出登录）
     *
     * @param request
     * @return
     */
    @Override
    public Boolean loginOut(HttpServletRequest request) {
        //判断是否登录
        Object object = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) object;
        Long currentUserId = currentUser.getId();
        if (currentUserId == null) {
            ThrowUtils.throwIf(true, ErrorCode.OPERATION_ERROR, "用户未登录");
        }
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        //将数据库中拿到的数据返回出去
        return true;
    }

    /**
     * 密码加密
     *
     * @param password
     * @return
     */
    @Override
    public String encryptPassword(String password) {
        final String SALT = "kui";
        // 密码加密逻辑
        return DigestUtils.md5DigestAsHex((SALT + password).getBytes());
    }

    /**
     * 脱敏用户信息
     *
     * @param user
     * @return
     */
    @Override
    public LoginUserVO loginUser(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 用户获取脱敏用户信息
     *
     * @param user
     * @return
     */
    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取脱敏用户列表
     *
     * @param userList
     * @return
     */
    @Override
    public List<UserVO> getUserList(List<User> userList) {
        if (userList == null) {
            return new ArrayList<>();
        }
        return userList
                .stream()
                .map(this::getUserVO)
                .collect(Collectors.toList());
    }

    /**
     * 获取查询条件
     *
     * @param userQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        String id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userAccount = userQueryRequest.getUserAccount();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField), sortOrder.equals("asc"), sortField);
        return queryWrapper;
    }

    /**
     * 判断是否是管理员
     *
     * @param user
     * @return
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserEnums.ADMIN.getValue().equals(user.getUserRole());
    }

}




